<?php

namespace App\Http\Controllers\Admin;

use App\Model\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Validator;

class CategoryController extends Controller
{
    /**
     * 查询分类
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = (new Category())->tree();
        return view('admin.cate.index',['data'=>$data]);
    }



    /**
     * 添加分类方法
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = Category::where('cate_pid',0)->get();
        return view('admin.cate.add',['data'=>$data]);
    }

    /**
     * 添加分类的提交方法
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = Input::except('_token');
        $rules=[
            'cate_name'=>'required',
        ];
        $message=[
            'cate_name.required'=>'分类名称不能为空!',
        ];
        $vali=Validator::make($input,$rules,$message);
        if($vali->passes()){
            $re = Category::create($input);
            if($re){
                return redirect('/admin/category');
            }else{
                return back()->with('errors','数据添加失败,请重新添加!');
            }
        }else{
            //返回并且传递出错误的信息
            return back()->withErrors($vali);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($cate_id)
    {
        $field = Category::find($cate_id);
        $data = Category::where('cate_pid',0)->get();
        return view('admin.cate.edit',['field'=>$field,'data'=>$data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $cate_id)
    {
        $request = $request->except('_token','_method');
        $re = Category::where('cate_id',$cate_id)->update($request);
        if($re){
            return redirect('/admin/category');
        }else{
            return back()->with('errors','数据修改失败,请重新修改!');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
